//
//  ViewController.m
//  网络连接之手机号码归属地查询
//
//  Created by My Mac on 2017/3/14.
//  Copyright © 2017年 My Mac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong) UITextField *textField;
@property(nonatomic,strong) UIButton *button;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /*
     * 在info.plist中加上网络连接的权限:Allow Arbitrary Loads 默认值设置为 YES
     */
    [self initView];
}

-(void)initView
{
    //设置视图背景色
    [self.view setBackgroundColor:[UIColor orangeColor]];
    //初始化文本框
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 80, 160, 45)];
    _textField.placeholder = @"请输入手机号";
    _textField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:_textField];
    
    //初始化按钮
    _button = [[UIButton alloc]initWithFrame:CGRectMake(230, 80, 50, 45)];
    [_button setTitle:@"查询" forState:UIControlStateNormal];
    _button.titleLabel.font = [UIFont systemFontOfSize:24];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:_button];
    //设置监听(响应事件)
    [_button addTarget:self action:@selector(getData) forControlEvents:UIControlEventTouchUpInside];
}

-(void)getData
{
    //获取输入的电话号码
    NSString *phone = _textField.text;
    //拼接网络地址（API接口）
    /*
     *  key:个人密钥
     *  phone:电话号码
     */
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://apicloud.mob.com/v1/mobile/address/query?phone=%@&key=*********",phone]];
    //网络请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //
    NSURLSession *session = [NSURLSession sharedSession];
    //创建任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //获取到数据
        NSString *text = [[NSString alloc]initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
        NSLog(@"%@",text);
        //将数据解析为字典
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dict);
        
        //刷新界面（更新UI）
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([dict[@"retCode"] intValue] == 200) {
                [self setAlertMessage:dict[@"result"][@"city"]];
            } else {
                [self setAlertMessage:dict[@"msg"]];
            }
        });
    }];
    [task resume];
}
//设置弹框
-(void)setAlertMessage:(NSString *)msg
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"查询结果" message:msg  preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
